package com.sqi.reactive.common.auth

import org.springframework.stereotype.Component

/**
 * @author: zhangfx
 * @create: 2018-07-04 10:30
 */
@Component
class RequestContext {

    var authPayload: AuthPayload
        get() = authPayloadThreadLocal.get()
        set(payload) {
            authPayloadThreadLocal.set(payload)
        }

    val loginUser: Subject?
        get() {
            val payload = authPayloadThreadLocal.get()
            return if (payload != null) {
                if (payload.subject is Subject) {
                    payload.subject as Subject?
                } else {
                    throw RuntimeException("错误的访问主体，需要是user, 实际是" + payload.type)
                }
            } else null
        }

    val currMicro: MicroSubject?
        get() {
            val payload = authPayloadThreadLocal.get()
            return if (payload != null) {
                if (payload.subject is MicroSubject) {
                    payload.subject as MicroSubject?
                } else {
                    throw RuntimeException("错误的访问主体，需要是micro, 实际是" + payload.type)
                }
            } else null
        }

    val currThirdSystem: ThirdSystemSubject?
        get() {
            val payload = authPayloadThreadLocal.get()
            return if (payload != null) {
                if (payload.subject is ThirdSystemSubject) {
                    payload.subject as ThirdSystemSubject?
                } else {
                    throw RuntimeException("错误的访问主体，需要是thirdsystem, 实际是" + payload.type)
                }
            } else null
        }

    companion object {
        private val authPayloadThreadLocal: ThreadLocal<AuthPayload> = InheritableThreadLocal()
    }
}